/**
 * @Copyright ®2015 Sinosoft Co. Ltd. All rights reserved.<br/>
 * 项目名称 : 电子商务云服务平台
 * 创建日期 : 2016年6月28日
 * 修改历史 : 
 *     1. [2016年7月14日]修改文件 by lijialun
 * 添加Javadoc注释，更新代码规范，静态工具类增加private构造函数
 */
package com.gavinwind.inspay.base;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gavinwind.inspay.common.dto.Response;
import com.gavinwind.inspay.common.logger.PlatformLogger;
import com.gavinwind.inspay.common.util.StringUtil;
import com.gavinwind.inspay.common.util.XStreamComponent;
import com.gavinwind.inspay.common.web.pagequery.PageGrid;
import com.gavinwind.inspay.common.web.pagequery.PageQueryModel;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**  
 * 【Controller基础类】
 * @Description: Controller基础类
 * @author Gavin
 * @date 2014-5-7 上午10:47:10 
 * @version V1.0  
 */
@SuppressWarnings("unchecked")
public class InspayBaseController {

    /**
     * @Fields logger : 日志记录工具
     */
    protected final PlatformLogger logger = PlatformLogger.getLogger(this.getClass());

    /**  
     * 【解析json的类型】
     * @author chenxin
     * @date 2014-5-15 上午10:58:24 
     * @version V1.0  
    */
    public enum JsonType {
        /** 
        * @Fields JSON_OBJECT : JSON_OBJECT
        */
        JSON_OBJECT, 
        
        /** 
        * @Fields JSON_ARRAY : JSON_ARRAY
        */
        JSON_ARRAY
    }

   
    /** 
     * 方法功能描述
     * @param cBinder
    */ 
    @InitBinder
    public void initBinder(WebDataBinder cBinder) {
        SimpleDateFormat tBateFormat = new SimpleDateFormat("yyyy-MM-dd");
        cBinder.registerCustomEditor(Date.class, new CustomDateEditor(tBateFormat, false));
    }

    /** 
     * 方法功能描述
     * @param cView
     * @return
     * @throws Exception
    */ 
    protected ModelAndView prepareModelAndView(String cView) throws Exception {
        // 此方法作用为初始化页面元素
        ModelAndView tModelAndView = new ModelAndView();
        tModelAndView.setViewName(cView);
        return tModelAndView;
    }

    
    /** 
     * 方法功能描述
     * @param cRes
     * @param cPageGrid
    */ 
    protected void renderPageGrid(HttpServletResponse cRes, PageGrid cPageGrid) {
        Response tRsponse = new Response();
        tRsponse.setObject(cPageGrid);
        XStreamComponent tXstreamComponent = XStreamComponent.newInstance();
        tXstreamComponent.alias(new Class[] { PageQueryModel.class, Response.class, PageGrid.class });
        String tXmlResponse = tXstreamComponent.toPageXML(tRsponse);
        renderXml(cRes, tXmlResponse);
    }

   
    /** 
     * 方法功能描述
     * @param cRes
     * @param cXmlResponse
    */ 
    protected void renderXml(HttpServletResponse cRes, String cXmlResponse) {
        try {
            cRes.setCharacterEncoding("UTF-8");
            cRes.setHeader("Content-type", "text/xml");
            cRes.getWriter().print(cXmlResponse);
        } catch (IOException ex) {
            logger.error("renderXml方法系统异常:",ex);
        }
    }

    /**
     * 分页查询初始化分页相关基础查询参数
     * @Title: getPageQueryModel 
     * @Description: TODO
     * @param cReq
     * @return
     */
    protected PageQueryModel getPageQueryModel(HttpServletRequest cReq) {
        PageQueryModel tPageQueryModel = new PageQueryModel();
        int tCurrentPage = StringUtil.parseStringToInt(cReq.getParameter("current"));
        tPageQueryModel.setPageSize(PageQueryModel.PAGE_SIZE);
        tPageQueryModel.setCurrentPage(tCurrentPage);
        return tPageQueryModel;
    }

    protected Map<String, Object> getRequestValue(HttpServletRequest cTequest) {
        Map<String, Object> tParaMap = new HashMap<String, Object>();
        Enumeration<String> tEnume = cTequest.getParameterNames();
        while (tEnume.hasMoreElements()) {
            String tKey = tEnume.nextElement();
            String tValue = cTequest.getParameter(tKey);
            tParaMap.put(tKey, tValue);
        }
        return tParaMap;
    }

    /**
     * 
     * 方法功能描述 向页面响应json数据
     * @Title: renderJsonData 
     * @Description: TODO
     * @author xupengfei@focoom.com.cn
     * @param cData 要解析的Java对象
     * @param cType 要解析的json类型
     * @param cRequest http请求对象
     * @param cResponse http响应对象
     * @throws Exception
     */
    protected void renderJsonData(Object cData, JsonType cType, HttpServletRequest cRequest, HttpServletResponse cResponse) throws Exception {
        String tStrJson = cType == JsonType.JSON_OBJECT ? JSONObject.toJSONString(cData).toString() : JSONArray.toJSONString(cData);
        PrintWriter tOut = cResponse.getWriter();
        tOut.print(tStrJson);
        logger.info(tStrJson);
        tOut.flush();
        tOut.close();
    }

    protected void renderJsonData(Object cData, JsonType cType, String cContent, HttpServletRequest cRequest, HttpServletResponse cResponse)
            throws Exception {
        String tStrJson = cType == JsonType.JSON_OBJECT ? JSONObject.toJSONString(cData) : JSONArray.toJSON(cData).toString();
        cResponse.setContentType("text/" + cContent + "; charset=utf-8");
        cResponse.setHeader("cache-control", "no-cache");
        PrintWriter tOut = cResponse.getWriter();
        tOut.print(tStrJson);
        tOut.flush();
        tOut.close();
    }

}